﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using LuaInterface;

namespace Twodi.Script
{
    public class LuaScriptFile : LuaScript
    {
        /// <summary>
        /// Caminho do arquivo de script.
        /// </summary>
        private String fileURL;

        /// <summary>
        /// Caminho do arquivo de script.
        /// </summary>
        public String FileURL
        {
            get { return fileURL; }
            set { fileURL = value; }
        }

        /// <summary>
        /// Construtor padrão.
        /// </summary>
        public LuaScriptFile()
        {

        }

        /// <summary>
        /// Construtor padrão.
        /// </summary>
        /// <param name="fileURL">Definir URL do arquivo de Script.</param>
        public LuaScriptFile(String fileURL)
        {
            this.FileURL = fileURL;
        }

        /// <summary>
        /// Construtor padrão.
        /// </summary>
        /// <param name="fileURL">Definir URL do arquivo. de Script.</param>
        /// <param name="variables">Variaveis do Script.</param>
        public LuaScriptFile(String fileURL, params String[] variables)
        {
            this.FileURL = fileURL;
            CreateVariables(variables);
        }

        /// <summary>
        /// Carregar script do arquivo.
        /// </summary>
        private void LoadScriptFromFile()
        {
            using (TextReader file = File.OpenText(FileURL))
            {
                String script = file.ReadToEnd();
                CreateVariables(CheckVariables(ref script));
                this.Script = script;
            }
        }

        /// <summary>
        /// Carregar script do arquivo no caminho informado.
        /// </summary>
        /// <param name="fileURL">Caminho do arquivo de script.</param>
        public void LoadScriptFromFile(String fileURL)
        {
            using (TextReader file = File.OpenText(fileURL))
            {
                String script = file.ReadToEnd();
                CreateVariables(CheckVariables(ref script));
                this.Script = script;
            }
        }

        /// <summary>
        /// Executar script na virtual machine.
        /// </summary>
        /// <param name="virtualMachine">Virtual machine do Lua aonde será executado o script.</param>
        /// <param name="variables">Pode ser usado para definir o valor da variavel de script.</param>
        /// <returns></returns>
        public override object[] Execute(Lua virtualMachine, params object[] variables)
        {
            LoadScriptFromFile();
            return base.Execute(virtualMachine, variables);
        }

    }
}
